/*
const value = 'https://example.com'; // 要存储的值
chrome.storage.sync.set({ movie_555: value }, () => {
    console.log('Value is set to ' + value);
});
*/

// 加载所有存储的数据并创建对应的表单元素
function restoreOptions() {
  // 获取所有 local 存储的值
  chrome.storage.local.get(null, (localItems) => {
    if (chrome.runtime.lastError) {
      console.error('Error retrieving local data:', chrome.runtime.lastError);
    } else {
      console.log('All local stored items:', localItems);

      // 获取所有 sync 存储的值
      chrome.storage.sync.get(null, (syncItems) => {
        if (chrome.runtime.lastError) {
          console.error(
            'Error retrieving sync data:',
            chrome.runtime.lastError
          );
        } else {
          console.log('All sync stored items:', syncItems);

          // 合并两个存储的结果
          const allItems = { ...localItems, ...syncItems };
          console.log('All stored items:', allItems);

          // null 代表获取所有的键值对
          var settingsDiv = document.getElementById('settings');
          for (var key in allItems) {
            var value = allItems[key];

            // 创建label
            var label = document.createElement('label');
            label.textContent = key + ': ';
            settingsDiv.appendChild(label);

            // 创建input
            var input = document.createElement('input');
            input.type = 'text';
            input.id = key;
            input.value = value;
            settingsDiv.appendChild(input);

            // 创建换行
            settingsDiv.appendChild(document.createElement('br'));
          }
        }
      });
    }
  });
}

// 保存对数据的更改
function saveOptions() {
  var inputs = document.getElementsByTagName('input');
  for (var i = 0; i < inputs.length; i++) {
    var key = inputs[i].id;
    var value = inputs[i].value;
    chrome.storage.sync.set({ [key]: value }, function () {
      console.log('Settings saved.');
    });
  }
}

// 绑定保存按钮的点击事件
document.getElementById('save').addEventListener('click', saveOptions);

// 初始化页面
document.addEventListener('DOMContentLoaded', restoreOptions);

// 点击设置555电影网站
document.getElementById('saveButton').addEventListener('click', () => {
  const value = document.getElementById('inputValue').value;
  if (!value) {
    return alert('请输入555电影网站地址');
  }
  chrome.storage.local.set({ movie_555: value }, () => {
    console.log('Value is set to ' + value);
  });
});
// 获取555网站的设置
document.getElementById('movieKey').addEventListener('click', () => {
  chrome.storage.local.get(['movie_555'], (result) => {
    console.log('Value currently is', result);

    console.log('Value currently is', result['movie_555']);
  });
});
